package com.jake.xpage.router;

import android.text.TextUtils;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class XPageRouteMapperManager {
    public static final String DEFAULT_ROUTE_MODULE = "main";
    @NonNull
    private final Map<String, XPageRouteMapper> mRouteMapper = new ConcurrentHashMap<>();
    @NonNull
    private final XPageRouteMapper.Callback mCallback;

    public XPageRouteMapperManager(@NonNull XPageRouteMapper.Callback callback) {
        mCallback = callback;
    }

    @MainThread
    public void registerRouteMapper(XPageRouteMapper mapper) {
        if (mapper == null) {
            return;
        }
        mapper.setCallback(mCallback);
        String moduleName = mapper.moduleName();
        if (TextUtils.isEmpty(moduleName)) {
            moduleName = DEFAULT_ROUTE_MODULE;
        }
        mRouteMapper.put(moduleName, mapper);
    }

    public Map<String, XPageRouteMapper> getRouteMappers() {
        return mRouteMapper;
    }

    @MainThread
    public void unregisterRouteMapper(XPageRouteMapper mapper) {
        if (mapper == null) {
            return;
        }
        String moduleName = mapper.moduleName();
        if (TextUtils.isEmpty(moduleName)) {
            moduleName = DEFAULT_ROUTE_MODULE;
        }

        XPageRouteMapper temp = mRouteMapper.get(moduleName);
        if (temp == mapper) {
            mRouteMapper.remove(moduleName);
        }
    }

    @MainThread
    public void openRoute(@NonNull XPageRoute route) {
        XPageRouteMapper mapper = mRouteMapper.get(route.module);
        if (mapper != null) {
            mapper.openRoute(route);
        }
    }

}
